package org.glut.saltedfish.servlet;


import com.google.gson.Gson;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.glut.saltedfish.domain.Product;
import org.glut.saltedfish.mapper.ProductMapper;
import org.glut.saltedfish.service.ProductService;
import org.glut.saltedfish.utils.MyBatisUti;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

import static java.lang.System.out;

@WebServlet("/products/search")
public class ProductController extends HttpServlet {
    private SqlSessionFactory sqlSessionFactory;
    private static final Gson gson = new Gson(); // 全局 Gson 实例（线程安全）

    @Override
    public void init() throws ServletException {
        sqlSessionFactory = MyBatisUti.getSqlSessionFactory();
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws ServletException, IOException {
        String keyword = req.getParameter("keyword");
        resp.setContentType("application/json;charset=UTF-8");

        try (SqlSession sqlSession = sqlSessionFactory.openSession();
             PrintWriter out = resp.getWriter()) {

            ProductMapper productMapper = sqlSession.getMapper(ProductMapper.class);
            ProductService productService = new ProductService(productMapper);

            List<Product> products = (keyword == null || keyword.trim().isEmpty())
                    ? productService.getAllProducts()
                    : productService.searchProductsByTitle(keyword);

            // 直接输出 JSON
            out.print(gson.toJson(products));

        } catch (Exception e) {
            resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
            out.print("{\"error\":\"Server Error\"}");
        }
    }
}